package com.gitlab.lucky.weixin.service;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.utils.HttpClientUtil;
import com.gitlab.lucky.common.utils.Template;
import com.gitlab.lucky.common.utils.TemplateMessageUtil;
import com.gitlab.lucky.common.weixin.WeixinUtil;
import com.gitlab.lucky.weixin.web.model.*;
import org.apache.ibatis.annotations.ResultMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-11-07 16:44
 **/
@Service
public class WeixinGzhMsgService {
    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinGzhMsgService.class);
    @Autowired
    private WeixinUtil weixinUtil;
    public static final String SERVICE_SEND_MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=%s";

    /**
     * 返回文本消息
     *
     * @return
     */
    public String resultText(String openId, String content, String formUserName) {
        ReplyTextMsg textMsg = new ReplyTextMsg();
        textMsg.setFromUserName(formUserName);
        textMsg.setToUserName(openId);
        textMsg.setCreateTime();
        //将XML消息的参数都转化内容回复给微信
        textMsg.setContent(content);
        textMsg.setMsgType(Constant.MSG_TYPE_TEXT);
        //将对象转化为XML
        String replyMsg = textMsg.Msg2Xml();
        //LOGGER.info("同步返回文本消息:openId="+openId+"---内容="+replyMsg);
        return replyMsg;
    }

    /**
     * 返回图文消息
     *
     * @return
     */
    public String resultNews(String openId, String hbUrl, String title, String description, String formUserName) {
        List<Article> ls = new ArrayList<>();
        Article article1 = new Article();
        article1.setTitle(title);
        article1.setDescription(description);
        article1.setPicurl("");
        article1.setUrl(hbUrl);
        ls.add(article1);
        ReplyNewsMsg rNewsMsg = new ReplyNewsMsg();
        rNewsMsg.setFromUserName(formUserName);
        rNewsMsg.setToUserName(openId);
        rNewsMsg.setCreateTime();
        rNewsMsg.setMsgType(Constant.MSG_TYPE_NEWS);
        rNewsMsg.setArticles(ls);
        rNewsMsg.setArticleCount(ls.size());
        String resultMsg = rNewsMsg.News2XML();
        //LOGGER.info("同步返回图文消息:openId="+openId+"---内容="+resultMsg);
        return resultMsg;
    }

    /**
     * 客服异步返回文本消息
     */
    public void resultServerText(String openId, String content, Integer platform) {
        String reqUrl = String.format(SERVICE_SEND_MSG_URL, weixinUtil.getAccessToken(platform));
        Text text = new Text();
        text.setContent(content);
        CustomerTextMsg customerTextMsg = new CustomerTextMsg();
        customerTextMsg.setMsgtype(Constant.MSG_TYPE_TEXT);
        customerTextMsg.setTouser(openId);
        customerTextMsg.setText(text);
        String json = JSONObject.toJSONString(customerTextMsg);
        HttpUtil.post(reqUrl, json);
        //LOGGER.info("异步返回文本消息:openId="+openId+"---内容="+content+"---"+JSONObject.toJSONString(post));
    }

    /**
     * 客服异步返回图文消息
     */
    public void resultServerNews(String openId, String title, String description, String url, String picUrl, Integer platform) {
        String reqUrl = String.format(SERVICE_SEND_MSG_URL, weixinUtil.getAccessToken(platform));
        CustomerNewsMsg customerNewsMsg = new CustomerNewsMsg();
        News news = new News();
        List<Article> ls = new ArrayList<>();
        Article article = new Article();
        article.setTitle(title);
        article.setDescription(description);
        article.setPicurl(picUrl);
        article.setUrl(url);
        ls.add(article);
        news.setArticles(ls);
        customerNewsMsg.setMsgtype(Constant.MSG_TYPE_NEWS);
        customerNewsMsg.setTouser(openId);
        customerNewsMsg.setNews(news);
        HttpUtil.post(reqUrl, JSONObject.toJSONString(customerNewsMsg));
        //LOGGER.info("异步返回图文消息:openId="+openId+"---内容"+JSONObject.toJSONString(post));
    }

    /**
     * 客服异步返回图片消息
     */
    public void resultServerImage(String openId, String mediaId, Integer platform) {
        //LOGGER.info("异步返回图片消息start,openId="+openId+"mediaId="+mediaId);
        String reqUrl = String.format(SERVICE_SEND_MSG_URL, weixinUtil.getAccessToken(platform));
        CustomerImageMsg customerImageMsg = new CustomerImageMsg();
        Image image = new Image();
        image.setMedia_id(mediaId);
        customerImageMsg.setImage(image);
        customerImageMsg.setMsgtype(Constant.MSG_TYPE_IMAGE);
        customerImageMsg.setTouser(openId);
        HttpUtil.post(reqUrl, JSONObject.toJSONString(customerImageMsg));
        //LOGGER.info("异步返回腿片消息:openId="+openId+"---内容=图片---"+JSONObject.toJSONString(post));
    }

    /**
     * 发送消息模版
     * @param openIds
     * @param platform
     * @param templateId
     * @param templateParams
     * @return
     */
    public String sendWarningByWechat(String openIds, Integer platform, String templateId,List<TemplateMessageUtil> templateParams,String url) {
        StringBuffer resBuff = new StringBuffer();
        String resJson = "";
        try {
            String accessToken = weixinUtil.getAccessToken(platform);
            String templateMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
            templateMsgUrl = templateMsgUrl.replace("ACCESS_TOKEN", accessToken);
            //封装请求体
            Template template = new Template();
            template.setTemplateId(templateId);
            template.setTemplateParamList(templateParams);
            template.setUrl(url);
            String[] openIdArr = openIds.split(",");
            if (openIdArr.length > 0) {
                for (String openID : openIdArr) {
                    template.setToUser(openID);
                    String paramStr = template.toJSON(url);
                    resJson = HttpClientUtil.doTemplateMsgPost(templateMsgUrl, paramStr);
                    System.out.println(resJson);
                    LOGGER.info(resJson);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return resJson;
    }

       /* public ResultMap sendWarningByWechat(String openIds, String content, String alarmDescriptions, String sendDateTime) {
            openIds = "obXBS5tGFgq1jDOJ_VwdIgEzt0ro";
            content = "尊敬的用户，您已获得邀请3倍积分奖励资格";
            sendDateTime = "正常";
        StringBuffer resBuff = new StringBuffer();
        try {
            String accessToken = weixinUtil.getAccessToken(3);
            String templateMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";
            templateMsgUrl = templateMsgUrl.replace("ACCESS_TOKEN", accessToken);

            //封装请求体
            Template template = new Template();
            template.setTemplateId("_w0p5tG4XYFOaEVnMBJ1gEPDjwphr37aaZI7MRz-10I");
            List<TemplateMessageUtil> templateParams = new ArrayList<>();
            String[] failures = alarmDescriptions.split("\\|\\|");
            String alarmDescStr = "邀请\\r\\n";
            if (failures != null && failures.length > 0) {
                for (String failure : failures) {
                    alarmDescStr += failure + "\\r\\n";
                }
                //去掉最后的换行符号
                alarmDescStr = alarmDescStr.substring(0, alarmDescStr.lastIndexOf("\\r\\n"));
            }
            String allStr = content + alarmDescStr;
            while (allStr.length() > 180) {
                alarmDescStr = alarmDescStr.substring(0, alarmDescStr.lastIndexOf("\\r\\n"))+"...";
                allStr = content + alarmDescStr;
            }
            TemplateMessageUtil first = new TemplateMessageUtil("first", content + "\\r\\n", "#DB1A1B");
            TemplateMessageUtil keyword1 = new TemplateMessageUtil("keyword1", alarmDescStr + "\\r\\n", "#DB1A1B");
            TemplateMessageUtil keyword2 = new TemplateMessageUtil("keyword2", sendDateTime + "", "#DB1A1B");
            TemplateMessageUtil keyword3 = new TemplateMessageUtil("keyword3", "2016/12/26——2017/12/25", "#DB1A1B");
            TemplateMessageUtil remark = new TemplateMessageUtil("remark", "感谢您的使用。", "");
            templateParams.add(first);
            templateParams.add(keyword1);
            templateParams.add(keyword2);
            templateParams.add(keyword3);
            templateParams.add(remark);
            template.setTemplateParamList(templateParams);
            String[] openIdArr = openIds.split(",");
            if (openIdArr.length > 0) {
                for (String openID : openIdArr) {
                    template.setToUser(openID);
                    String paramStr = template.toJSON();
                    String resJson = HttpClientUtil.doTemplateMsgPost(templateMsgUrl, paramStr);

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

}
